
Component({
  externalClasses: ["bar-class", 'item-class'],
  properties: {
    list:{
      type:Array,
      observer:function(){
        //console.log("observer list",this.data);
        if(this.data._itemWidth&&this.data._itemWidth>0)
          this.refresh();
      }
    },
    mg:Number,
    bg:{
      type:String,
      value:"white"
    },
    default:{
      type:Object,
      value:{}
    },
    type:{
      type:String,
      value:"nav"
    },
    current:{
      type:Number,
      observer: function(cur){
        this.setData({cur});
        this.trigger({source:""});
        this.scroll();
      }
    },
    width:{
      type:Number,
      value:750
    },
    itemWidth:{
      type:Number,
      value:-1
    },
    cancellable:{
      type:Number,
      value:0
    },
    autoscroll:{
      type:Number,
      value:1
    }
  },
  data: {
    scrollLeft: 0,
    cur:0
  },
  attached(){
    this.refresh();
  },
  methods: {
    refresh(){
      if (this.data.itemWidth == -1)
        var _itemWidth = Math.max(this.data.width / this.data.list.length, 150);
      else
        var _itemWidth = this.data.itemWidth;
      this.setData({ _itemWidth });
      this.scroll();
    },
    scroll(){
      if(this.data.cur>=0&&this.data.autoscroll&&this.data._itemWidth>0){
        let scrollLeft = (this.data.cur+0.5)*this.data._itemWidth-0.5*this.data.width;
        this.setData({scrollLeft})
      }
    },
    trigger({source=""}){
      let {cur:current} = this.data;
      if (current >= 0)
        var value = this.data.list[current];
      else
        var value = this.data.default;
      this.triggerEvent("change", { current, value, source});
    },
    switchNav({currentTarget:{dataset:{current}}}){
      if(current==this.data.cur) {
        if(this.data.cancellable)
          current=-1;
        else return
      }
      this.setData({cur:current});
      this.trigger({source:"touch"})
    }
  }
})
